import 'package:async/async.dart';
import 'package:bai_le_men_im/cmomon/utils.dart';
import 'package:bai_le_men_im/constants.dart';
import 'package:bai_le_men_im/conversation/groupMessagesPage.dart';
import 'package:bai_le_men_im/conversation/messagesPage.dart';
import 'package:bai_le_men_im/models/index.dart';
import 'package:bai_le_men_im/pages/search/searchAppBar.dart';
import 'package:bai_le_men_im/pages/search/searchAppBarInitKeyword.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import '../../constants.dart' show AppColors;
import 'package:intl/intl.dart';

class MatchKeywordForTarget extends StatefulWidget {
  final dynamic targetObj;
  final String displayName;
  final String keyword;
  MatchKeywordForTarget({this.targetObj, this.keyword, this.displayName});
  @override
  _MatchKeywordForTargetState createState() => _MatchKeywordForTargetState();
}

class _MatchKeywordForTargetState extends State<MatchKeywordForTarget> {
  String target;
  String targetType;
  String _keyword = '';
  List<Map<dynamic, dynamic>> searchResult = new List<Map<dynamic, dynamic>>();

  @override
  void initState() {
    super.initState();
    _keyword = widget.keyword;
    if (widget.targetObj is User) {
      User user = widget.targetObj;
      target = user.uid;
      targetType = 'Single';
    }
    if (widget.targetObj is Group) {
      Group group = widget.targetObj;
      target = group.target;
      targetType = 'Group';
    }
    search();
  }

  keywordControllerChangedHandler(String keyword) async {
    this.setState(() {
      _keyword = keyword;
      searchResult = null;
    });
  }

  search() async {
    final keyword = _keyword;
    var result =
        await FlutterWildfire.searchMessage(targetType, target, 0, keyword);
    this.setState(() {
      searchResult = new List<Map<dynamic, dynamic>>.from(result);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: SearchAppBarInitKeyword(
          keyword: widget.keyword,
          displayName: widget.displayName,
          onkeywordControllerChangedHandler: keywordControllerChangedHandler),
      body: Container(
        child: Column(
          children: <Widget>[
            Expanded(
              child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onPanDown: (_) {
                    FocusScope.of(context).requestFocus(FocusNode());
                  },
                  child: _keyword.isEmpty
                      ? EmptyKeyWord()
                      : (searchResult == null
                          ? Container(
                              decoration: BoxDecoration(
                                  border: Border(
                                      bottom:
                                          BorderSide(color: Colors.grey[300]))),
                              child: ListTile(
                                onTap: search,
                                title: Text(
                                  '搜索:"$_keyword"',
                                  style: TextStyle(color: Colors.blueAccent),
                                ),
                              ),
                            )
                          : renderResult())),
            )
          ],
        ),
      ),
    );
  }

  Widget renderResult() {
    if (searchResult == null) {
      return Container();
    }
    if (searchResult.length == 0) {
      return Container(
        padding: EdgeInsets.only(top: 30.0),
        child: Column(
          children: <Widget>[
            Center(
              child: Text.rich(
                TextSpan(children: [
                  TextSpan(text: '没有找到"', style: TextStyle(color: Colors.grey)),
                  TextSpan(
                      text: this._keyword,
                      style: TextStyle(
                          color: const Color(AppColors.TabIconActive))),
                  TextSpan(
                      text: '"相关聊天记录', style: TextStyle(color: Colors.grey))
                ], style: TextStyle(fontSize: 17.0)),
              ),
            )
          ],
        ),
      );
    }
    return Container(
      child: ListView.separated(
        separatorBuilder: (BuildContext context, int index) => Divider(
          height: 0.0,
        ),
        itemBuilder: (BuildContext context, int index) {
          var item = searchResult[index];
          return UserListTile(
              type: targetType,
              targetObj: widget.targetObj,
              target: item['conversation']['target'],
              sender: item['sender'],
              subtitle: colorKeyWord(item['content']['content']),
              serverTime: item['serverTime'],
              messageId: item['messageId']);
        },
        itemCount: searchResult.length,
      ),
    );
  }

  Widget colorKeyWord(String content) {
    String _keyword = this._keyword;
    List<String> _arrOthers = content.split(_keyword);
    List<TextSpan> _finalArr = new List<TextSpan>();
    for (int i = 0; i < _arrOthers.length; i++) {
      _finalArr.add(TextSpan(
          text: _arrOthers[i], style: TextStyle(color: Colors.black87)));
      if (i != _arrOthers.length - 1) {
        _finalArr.add(TextSpan(
            text: _keyword,
            style: TextStyle(color: const Color(AppColors.TabIconActive))));
      }
    }

    return Text.rich(
      TextSpan(children: [..._finalArr], style: TextStyle(fontSize: 16.0)),
      overflow: TextOverflow.ellipsis,
      maxLines: 1,
    );
  }
}

class UserListTile extends StatefulWidget {
  final String type;
  final String target;
  final String sender;
  final Widget subtitle;
  final int serverTime;
  final dynamic targetObj;
  final int messageId;
  UserListTile(
      {@required this.type,
      @required this.sender,
      this.targetObj,
      this.target,
      this.subtitle,
      this.serverTime,
      this.messageId});
  @override
  _UserListTileState createState() => _UserListTileState();
}

class _UserListTileState extends State<UserListTile> {
  final AsyncMemoizer _memoizer = AsyncMemoizer();
  getOtherSideInfo() {
    return _memoizer.runOnce(() async {
      Map result = await FlutterWildfire.getUserInfo(widget.sender, true);
      User user = User.fromJson(result);
      return user;
      // if (widget.type == 'Group') {
      //   Map result = await FlutterWildfire.getGroupInfo(widget.target);
      //   Group group = Group.fromJson(result);
      //   return group;
      // }
      print('未知的会话类型 conversation.type');
    });
  }

  @override
  Widget build(BuildContext context) {
    final DateFormat formatterYear = new DateFormat('yyyy-MM-dd');
    return FutureBuilder(
        future: getOtherSideInfo(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          String _displayName = '';
          String _avatar = '';
          Widget _pageWidget;

          if (snapshot.hasData) {
            User user = snapshot.data;
            _avatar = user.portrait;
            _displayName = user.displayName;
            if (widget.type == 'Single') {
              _pageWidget = MessagesPage(
                  user: widget.targetObj, messageId: widget.messageId);
            } else {
              _pageWidget = GroupMessagesPage(
                  groupInfo: widget.targetObj, messageId: widget.messageId);
            }
          }

          return ListTile(
            onTap: () async {
              if (_pageWidget == null) {
                return;
              }
              await Navigator.of(context)
                  .push(new MaterialPageRoute(builder: (context) {
                return _pageWidget;
              }));
            },
            leading: ClipRRect(
              borderRadius: BorderRadius.circular(Constants.AvatarRadius),
              child: myAvatar(_avatar),
            ),
            title: Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    _displayName,
                    style: TextStyle(fontSize: 12.0, color: Colors.grey),
                  ),
                  Text(
                    formatterYear.format(
                        DateTime.fromMillisecondsSinceEpoch(widget.serverTime)),
                    style: TextStyle(fontSize: 12.0, color: Colors.grey),
                  )
                  // "serverTime" -> 1570871219765
                ],
              ),
            ),
            subtitle: widget.subtitle,
          );
        });
  }
}

class EmptyKeyWord extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.only(top: 15.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '输入关键词搜索',
            style: TextStyle(color: Color.fromRGBO(214, 214, 214, 1.0)),
          )
        ],
      ),
    );
  }
}
